<?php
/* -----------------------------------------------------------------
 *                        Aveghe My Blog
 * -----------------------------------------------------------------
 * Aveghe My Blog: made your blog easy!
 * Copyright (C) 2008 Elia Contini
 * 
 * Aveghe My Blog is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * Aveghe My Blog is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 */

class DocController extends Zend_Controller_Action
	{
		protected $_flashMessenger = null;
		protected $preferences = null;
		
		public function init()
			{
				// general settings
				$this->view->setEncoding('UTF-8');
				$this->view->addHelperPath('aveghe/views/helpers', 'Aveghe_View_Helper');
				
				// preferences
				$this->preferences = Zend_Registry::get('preferences');
				/*while(list($key, $value) = each($this->preferences))
							echo "$key : $value <br />"; die;*/
				
				// for report
				$this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
				$this->view->report = $this->_flashMessenger->getMessages();
				
				$avegheNS = new Zend_Session_Namespace('avegheNS');
				
				if(!isset($avegheNS->userInfo))
					$this->_redirect('/user/login-required');
				else
					$this->view->userInfo = $avegheNS->userInfo;
			}
			
		public function indexAction()
			{
				$this->_forward('show-folder');
			}
		
		public function showFolderAction()
			{
				$avegheNS = new Zend_Session_Namespace('avegheNS');
				$docs = new Doc();
				
				$folder = $this->_getParam('id');
				if(!isset($folder))
					$avegheNS->currentFolder = 0;
				else
					$avegheNS->currentFolder = $folder;
				
				$this->view->parentFolder = $docs->getParentFolder($avegheNS->currentFolder);
				$this->view->currentFolder = $avegheNS->currentFolder;
				$this->view->docs = $docs->getFolder($avegheNS->currentFolder);
				
				$this->view->preferences = $this->preferences;
				$this->view->preferences['page_title'] = 'Contenuto della cartella ';
			}

		public function newDocumentAction()
			{
				// show form to create a new document
				$avegheNS = new Zend_Session_Namespace('avegheNS');

				if(isset($avegheNS->document))
					{
						$this->view->document = $avegheNS->document;
						unset($avegheNS->document);
					}

				$this->view->preferences = $this->preferences;
				$this->view->preferences['page_title'] = 'Crea un nuovo file';
				unset($avegheNS->currentDocument);
			}
			
		public function newFolderAction()
			{
				// show form to create a new folder
				$avegheNS = new Zend_Session_Namespace('avegheNS');
				$this->view->preferences = $this->preferences;
				$this->view->preferences['page_title'] = 'Crea una nuova cartella';
				$this->view->currentFolder = $avegheNS->currentFolder;
			}
			
		public function editAction()
			{
				$docID = (int) $this->_getParam('id');
				$avegheNS = new Zend_Session_Namespace('avegheNS');
				
				if(!isset($avegheNS->document))
					{
							$doc = new Doc();
							$this->view->doc = $doc->getFile($docID);
					}
				else
					{
						$this->view->doc = $avegheNS->document;
						unset($avegheNS->document);
					}
						
				$this->view->preferences = $this->preferences;
				$this->view->preferences['page_title'] = 'Modifica il file '.$this->view->doc['document_name'];
			}
		
		public function saveAction()
			{
				if($this->getRequest()->isPost())
					{
						if(array_key_exists('addImage', $this->getRequest()->getParams()))
							{
								// add an image to post
								$this->_forward('select-image');
							}
						else if(array_key_exists('addVideo', $this->getRequest()->getParams()))
							{
								// add a video to post
								$this->_forward('select-video');
							}
						else
							{
								// save post
								$this->_forward('save-file');
							}
					}
			}

		public function selectImageAction()
			{
        		$request = $this->getRequest();
        		
        		if($request->isPost())
        			{
        				$document = array( 'document_name' => $request->getPost('docTitle'),
        								   'document_description' => $request->getPost('docDescription'),
        								   'document_content' => $request->getPost('docText'),
										   'document_keywords' => $request->getPost('docKeywords'),
                                           'document_draft' => $request->getPost('docDraft'),
                                           'document_comments_enable' => $request->getPost('docComment')
        								 );

                        // existing file
        				if((int) $request->getPost('fileID') > 0)
        					$document['document_id'] = $request->getPost('fileID');
							
						$avegheNS = new Zend_Session_Namespace('avegheNS');
						$avegheNS->document = $document;
						
						$this->view->preferences = $this->preferences;
        			}
        		
        		//TODO - (Aveghe) manage GET request
			}
			
		public function addImageAction()
			{
				// disable autorendering for this action only
        		$this->_helper->viewRenderer->setNoRender();
        		
       			$avegheNS = new Zend_Session_Namespace('avegheNS');
				$document = $avegheNS->document;
				
				$alt = $this->getRequest()->getPost('imageAlt');
				$position = $this->getRequest()->getPost('imagePosition');
				
				// image directory for the current day
				date_default_timezone_set('Europe/Rome');
				$imgDirectory = 'img/'.date('Y-m-d').'/';
				if(!file_exists($imgDirectory))
					mkdir($imgDirectory);
				
				if($_FILES['image']['name'] != "")
	 				{
						
	 					if(!(ereg(".png$", $_FILES['image']['name']) || ereg(".gif$", $_FILES['image']['name']) || ereg(".jpg$", $_FILES['image']['name'])))  //check file extention
	    					;
	   					else if(file_exists($imgDirectory.$_FILES['image']['name']))                      //file already exists?
	    					;
	   					else
	    					{
	    						copy($_FILES['image']['tmp_name'], $imgDirectory.$_FILES['image']['name']); //save file
	      						@unlink($_FILES['image']['tmp_name']);
								
								$imgInfo = getimagesize($imgDirectory.$_FILES['image']['name']);	      						

	      						$document['document_content'] = $document['document_content'].'<img src="'.BASE_URL.'/'.$imgDirectory.$_FILES['image']['name'].'" class="'.$position.'" width="'.$imgInfo[0].'" height="'.$imgInfo[1].'" alt="'.$alt.'" />';
	      						$avegheNS->document = $document;

	      						$this->_flashMessenger->addMessage('<p class="success">Immagine aggiunta con successo.</p>'."\n");
							}
	 				}
	 			
				if(array_key_exists('document_id', $document))
					$this->_forward('edit');
				else
					$this->_forward('new-document');
			} 
		
		public function selectVideoAction()
			{
				$request = $this->getRequest();
        		
        		if($request->isPost())
        			{
        				$document = array( 'document_name' => $request->getPost('docTitle'),
        								   'document_description' => $request->getPost('docDescription'),
        								   'document_content' => $request->getPost('docText'),
										   'document_keywords' => $request->getPost('docKeywords'),
                                           'document_draft' => $request->getPost('docDraft'),
                                           'document_comments_enable' => $request->getPost('docComment')
        								 );

        				// existing file
        				if((int) $request->getPost('fileID') > 0)
        					$document['document_id'] = $request->getPost('fileID');
        								 
        				$avegheNS = new Zend_Session_Namespace('avegheNS');
						$avegheNS->document = $document;
						
						$this->view->preferences = $this->preferences;
        			}
        		
        		//TODO - (Aveghe) manage GET request
			}
			
		public function addVideoAction()
			{
				// disable autorendering for this action only
        		$this->_helper->viewRenderer->setNoRender();
        		
        		$request = $this->getRequest();
        		
        		if($request->isPost())
        			{
        				$url = (string)$request->getPost('videoURL');
        				
        				if($url != '')
        					{
        						// video ID 
        						$tmp = explode('=', $url);
        						$tmp = explode('&', $tmp[1]);
        						$videoID = $tmp[0];
        						
        						$html  = "<object width=\"425\" height=\"344\" type=\"application/x-shockwave-flash\" data=\"http://www.youtube.com/v/".$videoID."&amp;hl=it&amp;fs=1\">";
        						$html .= "\n\t<param name=\"movie\" value=\"http://www.youtube.com/v/".$videoID."&amp;hl=it&amp;fs=1\"></param>";
        						$html .= "\n\t<param name=\"allowFullScreen\" value=\"true\"></param>";
        						$html .= "\n</object>\n";
        						
        						$avegheNS = new Zend_Session_Namespace('avegheNS');
								$document = $avegheNS->document;
								
								$document['document_content'] = $document['document_content'].$html;
								$avegheNS->document = $document;
								
								if(array_key_exists('document_id', $document))
									$this->_forward('edit');
								else
									$this->_forward('new-document');
        					}
        			}
			}
			
		public function saveFileAction()
			{
				// disable autorendering for this action only
        		$this->_helper->viewRenderer->setNoRender();
        		
        		$avegheNS = new Zend_Session_Namespace('avegheNS');
        		
        		$request = $this->getRequest();
        		
        		if($this->getRequest()->isPost())
	        		{
	        			$fileName = trim($request->getPost('docTitle'));
	        			
						$document = array( 'document_parent_directory' => $avegheNS->currentFolder,
										   'document_owner' => $avegheNS->userInfo['user_id'],
										   'document_group' => $avegheNS->userInfo['user_id'],
								   		   'document_owner_permissions' => 'rw-',
										   'document_group_permissions' => 'r--',
										   'document_type' => $request->getPost('fileType'),
										   'document_name' => $request->getPost('docTitle'),
								 		 );
						
						// ID: che schifo di codice... da rivedere
						if((int)$request->getPost('fileID') > 0)
							$document['document_id'] = (int)$request->getPost('fileID');
						
						// draft
						if((string) $request->getPost('docDraft') == 'on')
							$document['document_draft'] = 1;
						else
							$document['document_draft'] = 0;
						
						// comments
						if((string) $request->getPost('docComment') == 'on')
							$document['document_comments_enable'] = 1;
						else
							$document['document_comments_enable'] = 0;
		
						// file type
						if($request->getPost('fileType') == '-')
							{
								$document['document_description'] = $request->getPost('docDescription');
								$document['document_keywords'] = $request->getPost('docKeywords');
								$document['document_content'] = $request->getPost('docText');
							}
							
	        			if($fileName == '' && $request->getPost('fileType') == '-')
	        				{
	        					$this->_flashMessenger->addMessage('<p class="warning">Specifica il titolo del post.</p>');
	        					$document['document_name'] = '';
								$avegheNS->document = $document;
								
								if(array_key_exists('document_id', $document))
									$this->_redirect('/doc/edit');
								else
									$this->_redirect('/doc/new-document');
	        				}
	        				
	        			if($fileName == '' && $request->getPost('fileType') == 'd')
	        				{
	        					$this->_flashMessenger->addMessage('<p class="warning">Specifica il nome della categoria.</p>');
	        					$this->_redirect('/doc/new-folder');
	        				}
							
						try
							{		 		 
								$doc = new Doc();		 
								if((int)$request->getPost('fileID') > 0)
									$doc->insertUpdateDocument((int)$request->getPost('fileID'), $document);
								else
									$doc->insertUpdateDocument('', $document);
								
								unset($avegheNS->currentDocument);
						
								if($request->getPost('fileType') == '-')
									$this->_flashMessenger->addMessage('<p class="success">Il file <strong>'.$request->getPost('docTitle').'</strong> &egrave; stato salvato.</p>'."\n");
								else
									$this->_flashMessenger->addMessage('<p class="success">La cartella <strong>'.$request->getPost('docTitle').'</strong> &egrave; stata salvata.</p>'."\n");
									
								$this->_redirect('/doc/show-folder/id/'.$avegheNS->currentFolder);
							}
						catch(Aveghe_File_Already_Exists_Exception $e)
							{
								if($request->getPost('fileType') == '-')
									{
										$this->_flashMessenger->addMessage('<p class="fail">Il post <strong>'.$request->getPost('docTitle').'</strong> esiste gi&agrave;!</p>'."\n");
										$document['document_name'] = '';
										$avegheNS->document = $document;
										
										if(array_key_exists('document_id', $document))
											$this->_redirect('/doc/edit');
										else
											$this->_redirect('/doc/new-document');
									}
								else
									$this->_flashMessenger->addMessage('<p class="fail">La categoria <strong>'.$request->getPost('docTitle').'</strong> esiste gi&agrave;!</p>'."\n");
							}
	        		}
	        		
	        	//TODO - (Aveghe) manage GET request
			}
	}
?>